<template>
  <div class="integral-editor">
    <el-dialog
      title="编辑积分"
      width="45%"
      :visible.sync="visible"
      @before-close="close()"
      :close-on-click-modal="false"
      :modal-append-to-body="true"
      :close-on-press-escape="false">
      <el-container style="min-height: 100%">
        <el-header>
          <el-steps :active="step" simple>
            <el-step title="1 基本信息" icon="el-icon-edit"/>
            <el-step title="2 积分细则" icon="el-icon-upload"/>
          </el-steps>
        </el-header>
        <el-main style="height: 100%;overflow: auto">
          <el-row v-show="parseInt(step) === 0" :gutter="20">
            <el-form :model="integralForm" :rules="integralFormRules" ref="integralForm" label-width="120px">
              <el-form-item prop="cateId" label="积分分类">
                <el-select v-model="integralForm.cateId" placeholder="请选择">
                  <el-option
                    v-for="item in cateList"
                    :key="item.value"
                    :label="item.name"
                    :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>

              <el-form-item prop="name" label="积分名称">
                <el-input type="text" @input="change($event)" v-model="integralForm.name"/>
              </el-form-item>

              <el-form-item prop="pCode" label="积分编码">
                <el-input v-model="integralForm.pCode"/>
              </el-form-item>
            </el-form>
          </el-row>
          <el-row v-show="parseInt(step) === 1" :gutter="20">
            <el-container style="height: 400px;border: 1px solid #CCCCCC">
              <el-header
                style="display: flex;justify-content: space-between;border-bottom: 1px solid #CCCCCC;height: 50px;line-height: 50px">
                <span>积分细则</span>
                <el-button type="text" class="addDetail" @click="addDetail">添加细则</el-button>
              </el-header>
              <el-main style="height: 100px;">
                <!--                <el-table :data="tableData">-->
                <!--                  <el-table-column prop="date" label="日期" width="140"/>-->
                <!--                  <el-table-column prop="name" label="姓名" width="120"/>-->
                <!--                  <el-table-column prop="address" label="地址"/>-->
                <!--                </el-table>-->
                <el-card class="car" v-for="(x,i) in By_laws" :key="i">
                  <el-form label-position="right" label-width="80px" :model="x" :ref="`by_laws${i}`" :rules="rules[i]">
                    <el-form-item label="名称" prop="ruleName">
                      <el-input v-model="x.ruleName"/>
                    </el-form-item>
                    <el-form-item label="编码" prop="cCode">
                      <el-input type="number" v-model="x.cCode"/>
                    </el-form-item>
                    <el-form-item label="规则管理" prop="checkedValue">
                      <el-checkbox-group v-model="x.checkedValue">
                        <el-checkbox label="one" name="type">每日一次</el-checkbox>
                        <el-checkbox label="cap" name="type">每日上限</el-checkbox>
                        <el-checkbox label="limitless" name="type">无限次</el-checkbox>
                      </el-checkbox-group>
                      <!--                      <el-input type="small"></el-input>-->
                    </el-form-item>
                    <el-form-item>
                      <el-button type="text" @click="del(i)">删除</el-button>
                    </el-form-item>
                  </el-form>
                </el-card>
              </el-main>
            </el-container>
          </el-row>
          <integral-addor ref="integralAddor"/>
        </el-main>
      </el-container>

      <div slot="footer">
        <el-button type="default" @click="close()">取消</el-button>
        <el-button type="primary" v-show="parseInt(step) > 0" @click="_up()" :loading="loading">上一步</el-button>
        <el-button type="primary" v-show="parseInt(step) < 1" @click="_down()" :loading="loading">下一步</el-button>
        <el-button type="primary" v-show="parseInt(step) > 0" @click="_submit()" :loading="loading">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import IntegralAddor from './integral-addor'

  export default {
    name: 'userPointsEditor',
    data() {
      return {
        addOrUpdateVisible: false,
        loading: false,
        step: 0,
        tableData: [],
        integralForm: {
          id: '',
          name: '',
          cateId: '',
          pCode: ''
        },
        By_lawsDome: {
          ruleName: '',
          cCode: '',
          id: '',
          checkedValue: []
        },
        By_laws: [{
          ruleName: '',
          cCode: '',
          id: '',
          checkedValue: ['one']
        }],
        id: '',
        cateList: [],
        integralFormRules: {
          name: [{required: true, message: '请填写积分名称'}],
          cateId: [{required: true, message: '请填写积分分类'}]
        },
        isEdit: false,
        visible: false
      }
    },
    computed: {
      rules() {
        return this.By_laws.map(x => ({
          ruleName: [{required: true, message: '细则名称不能为空', trigger: 'blur'}],
          cCode: [{required: true, message: '细则编码为6位数', trigger: 'blur'}],
          checkedValue: [{required: true, message: '请至少选择一个'}]
        }))
      }
    },
    components: {IntegralAddor},
    methods: {
      change() {
        this.$forceUpdate()
      },
      open(id) {
        this.By_laws = [{
          ruleName: '',
          cCode: '',
          checkedValue: ['one']
        }]
        this.integralForm.id = id
        this.step = 0
        this.loading = false
        this.visible = true
        this.classificationList()
        this.$nextTick(() => {
          this.$refs.integralForm.resetFields()
          if (id) {
            this.loadUserPoints(id)
            this.isEdit = true
          } else {
            this.isEdit = false
          }
        })
      },
      _up() {
        if (parseInt(this.step) === 1) this.step = 0
      },
      _down() {
        this.$refs.integralForm.validate(valid => {
          if (valid) {
            if (parseInt(this.step) === 0) this.step = 1
          }
        })
      },
      // del(i) {
      //   if (this.By_laws[i].id) {
      //     console.log(this.By_laws)
      //     this.$http({
      //       url: this.$http.adornUrl(`/integral-admin/integra/child/delete`),
      //       method: 'post',
      //       data: {
      //         'id': this.By_laws[i].id
      //       }
      //     }).then(res => {
      //       if (res.code == 200) {
      //         this.By_laws.splice(i, 1)
      //       }
      //     })
      //   } else {
      //     console.log('从数组溢出')
      //     this.By_laws.splice(i, 1)
      //   }
      // },
      // del(i) {
      //   this.$confirm(`确定要进行删除操作吗？`, '提示', {
      //     confirmButtonText: '确定',
      //     cancelButtonText: '取消',
      //     type: 'warning'
      //   })
      //   if (this.By_laws[i].id) {
      //     this.$http({
      //       url: this.$http.adornUrl(`/integral-admin/integra/child/delete`),
      //       method: 'post',
      //       data: {
      //         'id': this.By_laws[i].id
      //       }
      //     }).then(data => {
      //       if (data && data.code === 200) {
      //         this.$notify.success({
      //           title: '提示',
      //           message: '操作成功'
      //         })
      //         this.By_laws.splice(i, 1)
      //       } else {
      //         this.$notify.warning({
      //           title: '提示',
      //           message: data.msg
      //         })
      //       }
      //     })
      //   } else {
      //     this.By_laws.splice(i, 1)
      //   }
      // },
      del(i) {
        if (this.By_laws[i].id) {
          this.$confirm(`确定要进行删除操作吗？`, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.$http({
              url: this.$http.adornUrl(`/integral-admin/integra/child/delete`),
              method: 'post',
              data: {
                'id': this.By_laws[i].id
              }
            }).then(data => {
              if (data && data.code === 200) {
                this.$notify.success({
                  title: '提示',
                  message: '操作成功'
                })
                this.By_laws.splice(i, 1)
              } else {
                this.$notify.warning({
                  title: '提示',
                  message: data.msg
                })
              }
            })
          })
        } else {
          this.$notify.success({
            title: '提示',
            message: '删除成功!'
          })
          this.By_laws.splice(i, 1)
        }
      },
      _checkedValueMap(val) {
        let _json = {
          'one': false,
          'cap': false,
          'limitless': false
        }
        val.forEach(x => {
          switch (x) {
            case 'one':
              _json['one'] = true
              break
            case 'cap':
              _json['cap'] = true
              break
            case 'limitless':
              _json['limitless'] = true
              break
            default:
              break
          }
        })
        return JSON.stringify(_json)
      },
      _submit() {
        let arr = []
        this.By_laws.forEach((x, i) => {
          this.$refs[`by_laws${i}`][0].validate(valid => {
            arr.push(valid)
          })
        })
        arr = arr.filter(x => !x)
        if (arr.length) return false
        let data = {
          'id': this.integralForm.id,
          'cateId': this.integralForm.cateId,
          'pCode': this.integralForm.pCode,
          'ruleName': this.integralForm.name,
          'ruleList': this.By_laws.map(x => ({
            ruleName: x.ruleName,
            cCode: parseInt(x.cCode),
            id: x.id,
            checkedValue: this._checkedValueMap(x.checkedValue)
          }))
        }
        this.$http({
          url: this.$http.adornUrl(`/integral-admin/integral/parent/${!this.integralForm.id ? 'saveRule' : 'update'}`),
          method: 'post',
          data: {item: JSON.stringify(data)}
        }).then(res => {
          // eslint-disable-next-line eqeqeq
          if (parseInt(res.code) === 200) {
            this.visible = false
            this.$notify.success('保存积分规则成功')
            this.$emit('refresh')
          } else {
            this.$notify.error({
              title: '失败',
              message: res.msg
            })
          }
        })
      },
      addDetail() {
        this.By_lawsDome.ruleName = ''
        this.By_lawsDome.cCode = ''
        this.By_lawsDome.checkedValue = []
        this.By_laws.push(this.By_lawsDome)
        // this.addOrUpdateVisible = true
        // this.$nextTick(_ => {
        //   this.$refs.integralAddor.init()
        // })
      },
      // 获取数据列表
      classificationList() {
        this.$http({
          url: this.$http.adornUrl('/integral-admin/integral/cate/list'),
          method: 'post'
        }).then(res => {
          this.cateList = res.data
        })
      },
      async save() {
        this.loading = true
        let valid = await this.$refs.integralForm.validate()
        if (!valid) return false

        let res = await this.$http({
          method: 'post',
          data: this.integralForm,
          url: '/integral-admin/integral/saveParent/'
        })
        // + (this.isEdit ? 'update' : 'save')
        if (res.code === 200) {
          this.$message.success('保存积分规则成功')
          this.$emit('refresh')
          this.close()
          this.loading = true
        } else {
          this.loading = false
        }
      },
      close() {
        this.visible = false
      },
      async loadUserPoints(id) {
        let res = await this.$http({
          method: 'post',
          url: `/integral-admin/integral/parent/info/${id}`
        })
        console.log(res)
        this.integralForm = res.data.parentInfo
        this.integralForm.name = res.data.parentInfo.ruleName
        res.data.childList.forEach(x => {
          x.checkedValue = this._checkedValueParse(JSON.parse(x.checkedValue))
        })
        this.By_laws = res.data.childList
        // this.By_laws.forEach(x => {
        //   this.id = x.id
        // })
      },
      _checkedValueParse(val) {
        let _array = []
        for (let key in val) {
          if (val[key]) _array.push(key)
        }
        return _array
      }
    }
  }
</script>

<style>
  .addDetail {
    cursor: pointer;
    color: #0000ff;
  }

  .car {
    width: 100%;
    padding: 10px 10px;
    margin: 0 auto 20px;
  }

  .detail {
    width: 60%;
    height: 60px;
    border: 1px solid #CCCCCC;
  }
</style>
